#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
bool is_near(vector<vector<int>> path, int n1, int n2){
for(int i=0; i<path.size(); ++i){
if((path[i][0]==n1 && path[i][1]==n2) || (path[i][1]==n1 && path[i][0]==n2)){
return true;
}
}
return false;
}
bool reach(vector<vector<int>> path, vector<int> forbid, const vector<int> layer, int obj){
int val=obj;
for(int i=layer[obj]-1; i>0; --i){
vector<int> layer_val;
for(int j=0; j<layer.size(); ++j) if(layer[j]==i) layer_val.push_back(j);
for(int j=0; j<layer_val.size(); ++j){
if(is_near(path, val, layer_val[j])){
if(find(forbid.begin(), forbid.end(), layer_val[j])!=forbid.end()){
return false;
}
val=layer_val[j];
continue;
}
}
}
return true;
}
void fill_layer(const vector<vector<int>>& path, vector<int>& layer, int num, int pnum){
layer[num]=layer[pnum]+1;
vector<int> near;
for(int i=0; i<path.size(); ++i){
if(path[i][0]==num) near.push_back(path[i][1]);
if(path[i][1]==num) near.push_back(path[i][0]);
}
for(int near_val: near){
if(layer[near_val]) continue;
fill_layer(path, layer, near_val, num);
}
}
bool solution(int n, vector<vector<int>> path, vector<vector<int>> order){
bool answer=true;
vector<int> forbid, obj, layer(n, 0);
for(int i=0; i<order.size(); ++i){
obj.push_back(order[i][0]);
forbid.push_back(order[i][1]);
}
fill_layer(path, layer, 0, 1);
sort(obj.begin(), obj.end());
do{
int state=0;
vector<int> forbid_tmp=forbid;
for(int i=0; i<obj.size(); ++i){
if(reach(path, forbid_tmp, layer, obj[i])){
for(int j=0; j<order.size(); ++j) if(order[j][0]==obj[i]){
forbid_tmp.erase(remove(forbid_tmp.begin(), forbid_tmp.end(), order[j][1]), forbid_tmp.end());
state++;
break;
}
}
else break;
}
if(state==obj.size()){
return true;
}
}while(next_permutation(obj.begin(), obj.end()));
return false;
}
int main(void){
typedef vector<vector<int>> vector2;
int n1=9, n2=9, n3=9;
vector2 path1={
{0, 1}, {0, 3}, {0, 7}, {8, 1}, {3, 6}, {1, 2}, {4, 7}, {7, 5}
};
vector2 path2={
{8, 1}, {0, 1}, {1, 2}, {0, 7}, {4, 7}, {0, 3}, {7, 5}, {3, 6}
};
vector2 path3={
{0, 1}, {0, 3}, {0, 7}, {8, 1}, {3, 6}, {1, 2}, {4, 7}, {7, 5}
};
vector2 order1={{8, 5}, {6, 7}, {4, 1}};
vector2 order2={{4, 1}, {5, 2}};
vector2 order3={{4, 1}, {8, 7}, {6, 5}};
cout<<"result1: "<<solution(n1, path1, order1)<<endl;
cout<<"result2: "<<solution(n2, path2, order2)<<endl;
cout<<"result3: "<<solution(n3, path3, order3)<<endl;
return 0;
}